<template>
  <slide-view
    v-loading="loading"
    :no-listener-class="noListenerClass"
    :body-style="{padding: 0, height: '100%'}"
    class="d-view"
    xs-empty-icon="nopermission"
    :xs-empty-text="$t('oa.workLog.1eca431db3a028e149b26e96a4d45ae1')"
    @afterEnter="viewAfterEnter"
    @close="hideView">
    <div v-if="detail" direction="column" align="stretch" class="main">
      <wk-detail-header
        :title="$t('oa.workLog.5b9f2ee86aafe86f52c8fddac9604f1e')"
        :dropdowns="moreDropdowns"
        @command="moreDropdownsClick" />
      <div class="main__bd">
        <!-- 基本信息 -->
        <div class="main__bd--info">
          <div class="content">
            <log-fields-view :fields="fieldsDetail" />
          </div>

          <picture-list-view
            v-if="detail.img.length !== 0"
            :list="detail.img" />

          <flexbox
            v-if="detail.sendUserList && detail.sendUserList.length"
            class="send-list">
            <span class="send-list__label">
              {{ $t('oa.workLog.3c332196a01b5c87d8b6f2c7725da49a') }}
            </span>
            <!-- <span
                v-for="(item, index) in detail.sendUserList"
                :key="index"
                class="send-list__user">
                <xr-avatar
                  :id="item.userId"
                  :name="item.realname"
                  :size="32"
                  :src="item.img"
                  :disabled="false"
                  trigger="hover" />
              </span> -->
            <el-tooltip
              v-for="(item, index) in showSendUserList"
              :key="index"
              :class="{'is-close': allSendUserDeptList.length > maxSendShowCount}"
              placement="top"
              :content="item.realname || item.name"
              class="send-user">
              <xr-avatar
                :id="item.userId"
                :name="item.realname || item.name"
                :size="32"
                :disabled="!item.userId"
                :src="item.img" />
            </el-tooltip>
            <el-dropdown
              v-if="allSendUserDeptList.length > maxSendShowCount"
              trigger="click"
              :hide-on-click="false">
              <el-button class="dropdown-btn">
                +{{ allSendUserDeptList.length - maxSendShowCount }}
              </el-button>
              <el-dropdown-menu slot="dropdown" class="send-list-dropdown">
                <el-dropdown-item
                  v-for="(item,index) in closeSendUserDeptList"
                  :key="index"
                  class="send-list-dropdown-list">
                  <p class="send-list-dropdown-text">
                    {{ item.realname || item.name }}
                  </p>
                  <!-- <i
                    class="el-icon-close send-list-dropdown-i"
                    @click="deleteSendList(item, index + 5)" /> -->
                </el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
          </flexbox>

          <!-- 附件 -->
          <div v-if="detail.file.length" class="section">
            <div class="section__hd">
              <!-- <i class="wukong wukong-file" /> -->
              <span>
                {{ $t('oa.workLog.1891327788c09211d66f401f14e15de9') }}
              </span>
              <span>({{ detail.file.length }})</span>
            </div>
            <div class="section__bd">
              <file-cell :file-list="detail.file" />
            </div>
          </div>

          <!-- 相关信息 -->
          <div v-if="Object.keys(relatedListData).length > 0" class="section">
            <div class="section__hd">
              <!-- <i class="wukong wukong-relevance" /> -->
              <span>
                {{ $t('oa.workLog.3c99900e5e1f1230ce35967c5c208dd3') }}
              </span>
            </div>
            <div class="section__bd">
              <related-business
                ref="relatedBusiness"
                :margin-left="'0'"
                :all-data="relatedListData"
                :show-add-btn="false" />
            </div>
          </div>

          <div v-if="detail.getBulletin == 1" class="section">
            <div class="section__hd">
              <!-- <i class="wk wk-icon-briefing" /> -->
              <span>
                {{ $t('oa.workLog.a33c69aa84c34278e2e585897b020f2f') }}
              </span>
            </div>
            <div class="section__bd">
              <report-menu :list="reportList" @select="reportSelect" />
            </div>
          </div>

          <fav-list
            :is-favour="detail.isFavour"
            :data="detail.favourUser"
            @fav="favourClick" />
        </div>

        <!-- 回复 -->
        <el-tabs value="commont" type="border-card" class="commont">
          <el-tab-pane
            :label="$t('oa.workLog.a8110a987ed321644d6ce000661d5ae2')"
            name="commont">
            <reply-comment
              ref="f_reply"
              v-loading="commentLoading"
              @toggle="closeOtherReply"
              @reply="handleReply" />
            <comment-list
              v-if="replyList.length > 0"
              ref="comment_list"
              :props="commentListProps"
              :list="replyList"
              @delete="deleteComment"
              @close-other-reply="$refs.f_reply.toggleFocus(true)" />
          </el-tab-pane>
        </el-tabs>
      </div>
    </div>
    <!-- 销售简报列表 -->
    <report-list
      :show.sync="reportListShow"
      :title="reportData.title"
      :placeholder="reportData.placeholder"
      :crm-type="reportData.crmType"
      :request="reportData.request"
      :params="reportData.params"
      :record-request="reportData.recordRequest"
      :field-list="fieldReportList"
      :paging="reportData.paging"
      :sortable="reportData.sortable" />
  </slide-view>
</template>

<script>
import {
  journalQueryByIdAPI,
  journalQueryRecordCountAPI,
  journalQueryBulletinByTypeAPI,
  oaLogFavourOrCancelAPI,
  journalInformationAPI
} from '@/api/oa/journal'
import {
  setCommentAPI,
  deleteCommentAPI,
  queryCommentListAPI
} from '@/api/oa/common'

import SlideView from '@/components/SlideView'
import PictureListView from '@/components/PictureListView'
import FileCell from '@/components/FileCell'
import RelatedBusiness from '@/components/RelatedBusiness'
import ReportMenu from './ReportMenu'
import ReportList from '@/views/crm/workbench/components/ReportList'
import ReplyComment from '@/components/ReplyComment'
import CommentList from '@/components/CommentList'
import FavList from './FavList'
import LogFieldsView from './LogFieldsView'
import WkDetailHeader from '@/components/Page/WkDetailHeader'

import { mapGetters } from 'vuex'
import { separator } from '@/filters/vueNumeralFilter/filters'
import { getReportFieldList } from '../utils'

export default {
  // 日志详情
  name: 'LogDetail',
  components: {
    SlideView,
    PictureListView,
    FileCell,
    RelatedBusiness,
    ReportMenu,
    ReportList,
    ReplyComment,
    CommentList,
    FavList,
    WkDetailHeader,
    LogFieldsView
  },
  props: {
    id: [String, Number],
    noListenerClass: {
      type: Array,
      default: () => {
        return ['el-table__body']
      }
    }
  },
  data() {
    return {
      loading: false,
      detail: null,
      fieldsDetail: [], // 自定义字段等详情
      // 简报信息
      reportList: [
        {
          type: 'customer',
          key: 'customerCount',
          info: this.$t('oa.workLog.6a373c0d1eba3fd407ceb19f2ad7fe37'),
          count: 0,
          name: this.$t('oa.workLog.7ea4a39b814b8f68992f2b7e033bdaa1')
        },
        {
          type: 'business',
          key: 'businessCount',
          info: this.$t('oa.workLog.0c3082d4a1f67646cd70657305419a0c'),
          count: 0,
          name: this.$t('oa.workLog.2a2bfd0c24279af826ed40626496b52a')
        },
        {
          type: 'contract',
          key: 'contractCount',
          info: this.$t('oa.workLog.14f08edeae723e9592c05d3d11dc0700'),
          count: 0,
          name: this.$t('oa.workLog.2a9e7993852ef577932fcd0ded5b3bb8')
        },
        {
          type: 'receivables',
          key: 'receivablesMoney',
          info: this.$t('oa.workLog.02be4a8f6c7482a1aa704512b1095823'),
          count: 0,
          name: this.$t('oa.workLog.21a563266744e99eba6974e5103dcc46')
        },
        {
          type: 'record',
          key: 'recordCount',
          info: this.$t('oa.workLog.ce7041207b4f8f3b2e7a922b51b6f28b'),
          count: 0,
          name: this.$t('oa.workLog.41e2b405955e0bba423243ef4ec78432')
        }
      ],

      // 简报预览
      reportListShow: false,
      fieldReportList: null,
      reportData: {
        title: '',
        placeholder: '',
        crmType: '',
        request: null,
        recordRequest: journalQueryBulletinByTypeAPI,
        params: null,
        paging: true,
        sortable: false
      },

      // 回复
      commentLoading: false,
      replyList: [],
      maxSendShowCount: 5,

      moreDropdowns: [{
        command: 'print',
        name: this.$t('oa.workLog.9e99400d958e496eb8cff6f8e8af30ee')
      }]
    };
  },
  computed: {
    ...mapGetters([
      'userInfo'
    ]),
    /**
     * 相关信息
     */
    relatedListData() {
      const tempsData = {}
      const keys = ['contacts', 'customer', 'business', 'contract']
      for (let index = 0; index < keys.length; index++) {
        const key = keys[index]
        const list = this.detail[`${key}List`] || []
        if (list.length > 0) {
          tempsData[key] = list
        }
      }
      return tempsData
    },
    // 日志标题
    logTitleName() {
      return {
        1: this.$t('oa.workLog.ca0b854bd2102653408bfc1f60d2badb'),
        2: this.$t('oa.workLog.b2b8a492ef797997ff9fdfbfc61d3c5b'),
        3: this.$t('oa.workLog.09e362382c664ae75404be33ec9482c9')
      }[this.detail.categoryId] + this.$t('oa.workLog.bbdddde30a26c149c50eba487111e692')
    },
    logNextTitleName() {
      return {
        1: this.$t('oa.workLog.93a14d4222432874f66de6dd60e2bf3d'),
        2: this.$t('oa.workLog.0197dc86e9d14a07b0ed1792fdfa0dac'),
        3: this.$t('oa.workLog.ce83d873df6ab2ba59c15aadec2ccfae')
      }[this.detail.categoryId] + this.$t('oa.workLog.182b5cf906392e050402e4f0e64fe3d9')
    },

    // 评论列表配置
    commentListProps() {
      return {
        addRequest: setCommentAPI, // 添加请求和参数
        addParams: { typeId: this.id, type: '2' }, // 3 知识库 2 日志 1 任务
        replyKey: 'pid', // 日志 任务 pid  阶段 replyId
        replyValueKey: 'userId', // 获取值的keys 日志 任务 userId  阶段 user.userId
        deleteRequest: deleteCommentAPI, // 删除请求和参数
        deleteParams: null
      }
    },

    // 展示的发送人
    showSendUserList() {
      return this.allSendUserDeptList.slice(0, this.maxSendShowCount)
    },

    // 全部发送人
    allSendUserDeptList() {
      const defaultSendUserList = (this.detail.sendUserList || []).map(item => {
        item.disabled = true
        return item
      })
      const defaultSendDeptList = (this.detail.sendDeptList || []).map(item => {
        item.disabled = true
        return item
      })

      return defaultSendUserList.concat(defaultSendDeptList)
    },

    // 闭合起来的员工和部门
    closeSendUserDeptList() {
      return this.allSendUserDeptList.slice(this.maxSendShowCount)
    }
  },
  watch: {
    id() {
      this.viewAfterEnter()
    }
  },
  mounted() {},

  beforeDestroy() {},

  methods: {
    /**
     * @description: 获取字段信息
     * @return {*}
     */
    getFieldsInfo() {
      this.loading = true
      journalInformationAPI({ id: this.id })
        .then(res => {
          this.loading = false
        })
        .catch(() => {
          this.loading = false
          this.hideView()
        })
    },

    /**
     * @description: 更多事件
     * @return {*}
     */
    moreDropdownsClick(command) {
      if (command === 'print') {
        this.$router.push({
          name: 'logPrint',
          query: {
            id: this.detail.logId,
            templateId: this.detail.categoryId
          }
        })
      }
    },

    /**
     * 页面展示发请求
     */
    viewAfterEnter() {
      this.detail = null
      this.getDetail()
      this.getCommentList()
    },

    /**
     * 详情
     */
    getDetail() {
      this.loading = true

      Promise.all([
        journalQueryByIdAPI({ logId: this.id }),
        journalInformationAPI({ id: this.id })
      ]).then(resArr => {
        if (resArr[0]) {
          this.detail = resArr[0].data
          if (this.detail.getBulletin == 1) {
            const data = this.detail.bulletin || {}
            this.reportList = this.reportList.map(item => {
              if (item.key == 'receivablesMoney') {
                data.receivablesMoney = separator(data.receivablesMoney || 0)
              }
              item.count = data[item.key]
              item.name = `${item.info} ${item.count}`
              return item
            })
          }
        }

        if (resArr[1]) {
          this.fieldsDetail = resArr[1].data || []
        }

        this.loading = false
      }).catch(() => {
        this.loading = false
      })
    },

    /**
     * 关闭页面
     */
    hideView() {
      this.$emit('close')
      this.$emit('hide-view')
    },

    /**
     * 简报预览
     */
    reportSelect(item, data) {
      data = this.detail

      if (item.type) {
        this.reportData.title = this.$t('oa.workLog.8157ebf9f8157136e46d5e23e2c0309c', { 1: item.info })
        this.reportData.placeholder = {
          customer: this.$t('oa.workLog.6b3f9497f1cf8fa8fc6a4b8fd4b9be99'),
          business: this.$t('oa.workLog.ac449bb957dfd616165ac57b8432d443'),
          contract: this.$t('oa.workLog.5d0512c9bb551f6ee54b3b5f8d2d2d26'),
          receivables: this.$t('oa.workLog.be5f6eea32cea110eb4fb4f97e69014a'),
          record: ''
        }[item.type]

        this.reportData.crmType = item.type
        // data 存在 是已添加日志预览  不存在为页面顶部 销售简报预览
        this.reportData.params = data ? { logId: data.logId } : { today: 1 }

        // type   1 客户 2 商机 3 合同 4 回款 5 跟进记录
        this.reportData.params.type = {
          customer: 1,
          business: 2,
          contract: 3,
          receivables: 4,
          record: 5
        }[item.type]

        if (item.type == 'record') {
          this.fieldReportList = [
            {
              label: this.$t('oa.workLog.5df25c6fb0b002a88485b82bbe96d357'),
              prop: 'crmType',
              width: 300
            },
            {
              label: this.$t('oa.workLog.5c807bc5e25a6bb6ecea54b76580a37f'),
              prop: 'count'
            }
          ]
          this.reportData.request = journalQueryRecordCountAPI
          this.reportData.paging = false
          this.reportData.sortable = false
        } else {
          this.fieldReportList = getReportFieldList(item.type)
          this.reportData.request = journalQueryBulletinByTypeAPI
          this.reportData.paging = true
          this.reportData.sortable = 'custom'
        }

        this.reportListShow = true
      }
    },

    /**
     * 评论逻辑
     */
    getCommentList() {
      queryCommentListAPI({
        typeId: this.id,
        type: 2 // 任务1 日志2
      })
        .then(res => {
          const list = res.data || []
          this.replyList = list
          // this.replyList = list.sort((a, b) => {
          //   return new Date(b.createTime) - new Date(a.createTime)
          // }) || []
        })
        .catch(() => {})
    },

    closeOtherReply(flag) {
      if (!flag && this.$refs.comment_list) {
        this.$refs.comment_list.closeReply()
      }
    },

    deleteComment(index) {
      this.replyList.splice(index, 1)
    },

    /**
     * 日志评论
     */
    handleReply(data) {
      this.commentLoading = true
      setCommentAPI({
        content: data,
        ...this.commentListProps.addParams
      }).then(res => {
        res.data.user = {
          userId: this.userInfo.userId,
          realname: this.userInfo.realname,
          img: this.userInfo.img
        }
        res.data.childCommentList = []
        // this.$emit('add-comment', {
        //   data: res.data,
        //   index: this.index
        // })
        this.$refs.f_reply.commentsTextarea = ''
        this.replyList.push(res.data)
        this.commentLoading = false
      }).catch(() => {
        this.commentLoading = false
      })
    },

    /**
     * 点赞
     */
    favourClick() {
      oaLogFavourOrCancelAPI({
        isFavour: !this.detail.isFavour,
        logId: this.detail.logId
      }).then(res => {
        const resData = res.data || {}
        this.detail.isFavour = resData.isFavour
        this.detail.favourUser = resData.favourUser
      })
        .catch(() => {})
    }

  }
}
</script>

<style lang="scss" scoped>
.main {
  position: relative;
  height: 100%;
  background: #f5f6f9;

  &__bd {
    height: calc(100% - 40px);
    overflow: auto;

    &--info {
      padding: 0 20px 10px;
      background: white;
    }
  }
}

.d-view {
  position: fixed;
  top: $--detail-view-top;
  right: 0;
  bottom: 0;
  width: $--detail-width-base;
  min-width: 926px;
  padding: 15px;
  padding: 0 !important;
  background-color: white;
}

// 日志内容
.content {
  padding-top: 30px;

  .content-box {
    margin-bottom: 16px;
    font-size: 14px;

    &:last-child {
      margin-bottom: 16px;
    }

    .content-title {
      margin-bottom: 8px;
      color: $--color-n200;
    }

    .content-text {
      line-height: 1.5;
      word-wrap: break-word;
      white-space: pre-wrap;
    }
  }
}

.wk-detail-header {
  padding: 30px 20px 0;
  background: white;
}

.send-list {
  padding: 8px 0;

  &__label {
    color: $--color-n200;
  }

  &__user {
    position: relative;
    display: inline-block;
  }

  &__user + &__user {
    margin-left: 7px;
  }
}

// 详情其他模块
.section {
  padding: 10px 0;

  &__hd {
    span {
      font-size: 16px;
      font-weight: 600;
    }

    .wk {
      margin-right: 5px;
      font-size: 15px;
      color: #363636;
    }
  }

  &__bd {
    padding-left: 0;
    margin-top: 15px;
  }
}

// 销售简报
.report-menu {
  padding: $--interval-base;
  background-color: $--background-color-base;
  border-radius: $--border-radius-base;
}

// 详情
.commont {
  margin-bottom: 50px;
  box-shadow: none;

  ::v-deep .el-tabs__item {
    top: 2px;
    margin-top: -2px;
    font-size: 12px;
  }

  ::v-deep .el-tabs__nav-scroll {
    min-height: 39px;
  }

  ::v-deep .el-tabs__item.is-active {
    border-top: 2px solid $--color-primary;
  }

  ::v-deep .el-tabs {
    height: calc(100% - 15px) !important;
  }

  // ::v-deep .el-tabs__content {
  //   height: calc(100% - 40px) !important;
  //   padding: 0;
  //   overflow: hidden;
  //   position: relative;

  //   .el-tab-pane {
  //     height: 100%;
  //     overflow: hidden;
  //   }
  // }
}

// 发送人
.send-user {
  position: relative;
  display: inline-block;

  &.is-close {
    border: 3px solid #fff;
    border-radius: 50%;
  }

  &.is-close + &.is-close {
    margin-left: -13px !important;
  }
}

.send-user + .send-user {
  margin-left: 7px;
}

.send-list-dropdown {
  width: 200px;
  max-height: 300px;
  overflow-y: auto;

  &-list {
    position: relative;
    display: flex;
    align-items: center;
    padding-top: 5px;
    padding-bottom: 5px;
    border-left: 2px solid $--color-white;

    &:hover {
      background: $--color-n20 !important;
      border-left: 2px solid $--color-b400;
    }

    &:hover .send-list-dropdown-i {
      display: inline-block;
      color: $--color-n500;
    }

    &:hover .send-list-dropdown-text {
      color: $--color-n500;
    }
  }

  &-text {
    display: inline-block;
    width: 80px;
    height: 32px;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }

  &-i {
    position: absolute;
    top: 18px;
    right: 10px;
    display: none;
    margin-left: 60px;
  }
}
</style>
